package com.briup.es.service.impl;

import com.briup.es.domain.bean.OrderItem;
import com.briup.es.domain.bean.Shopcar;
import com.briup.es.domain.vo.OrderItemVO;
import com.briup.es.mapper.OrderItemMapper;
import com.briup.es.service.OrderItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderItemServiceImpl implements OrderItemService {

    @Resource
    private OrderItemMapper mapper;

    @Transactional
    public void generatorOrderItem(String orderId, List<Shopcar> shopcars) {
        // 根据购物车项的数量决定需要生成多少个订单项对象数据
        // 先根据购物车项生成对应的订单项对象
        List<OrderItem> orderItems = shopcars.stream()
                // 将购物车项对象转换为 订单项对象
                .map(shopcar -> initOrderItem(orderId, shopcar))
                // 将所有的订单项对象收集成一个集合
                .collect(Collectors.toList());
        // 直接将所有的订单项数据存入数据库中
        mapper.addOrderItems(orderItems);
    }

    @Override
    public List<OrderItemVO> queryByOrderId(String orderId) {
        return mapper.queryByOrderId(orderId);
    }

    private OrderItem initOrderItem(String orderId, Shopcar shopcar) {
        return OrderItem.builder()
                .bookId(shopcar.getBookId())
                .orderId(orderId)
                .num(shopcar.getNum())
                .build();
    }
}
